package com.longcai.cm.base.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import com.longcai.cm.base.filter.KickoutSessionFilter;
import com.longcai.cm.base.filter.SimpleFormAuthenticationFilter;
import com.longcai.cm.base.shiro.MyShiroRealm;
import com.longcai.cm.common.utils.StringUtils;
import com.longcai.cm.utils.LogUtil;
import org.apache.shiro.authc.pam.FirstSuccessfulStrategy;
import org.apache.shiro.codec.Base64;
import org.apache.shiro.crypto.AesCipherService;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.session.SessionListener;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.CookieRememberMeManager;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.crazycake.shiro.RedisCacheManager;
import org.crazycake.shiro.RedisManager;
import org.crazycake.shiro.RedisSessionDAO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.security.Key;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {


    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Value("${spring.redis.host}")
    private String host;

    @Value("${spring.redis.port}")
    private int port;

    @Value("${spring.redis.timeout}")
    private int timeout;

    @Value("${spring.redis.password}")
    private String password;

    @Value("${server.servlet.session.timeout}")
    private int tomcatTimeout;

    @Bean
    public static LifecycleBeanPostProcessor getLifecycleBeanPostProcessor() {
        return new LifecycleBeanPostProcessor();
    }


    /**
     * ShiroFilterFactoryBean 处理拦截资源文件问题。
     * 注意：单独一个ShiroFilterFactoryBean配置是或报错的，因为在
     * 初始化ShiroFilterFactoryBean的时候需要注入：SecurityManager
     * <p>
     * Filter Chain定义说明 1、一个URL可以配置多个Filter，使用逗号分隔 2、当设置多个过滤器时，全部验证通过，才视为通过
     * 3、部分过滤器可指定参数，如perms，roles
     */
    @Bean
    public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();

        logger.debug("[CM]---[Shiro]拦截器工厂类注入-------------------完成");

        // 必须设置 SecurityManager
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        // 如果不设置默认会自动寻找Web工程根目录下的"/login"页面
        shiroFilterFactoryBean.setLoginUrl("/master/login");
        // 登录成功后要跳转的链接
        shiroFilterFactoryBean.setSuccessUrl("/master/index");
        // 未授权界面;
        shiroFilterFactoryBean.setUnauthorizedUrl("/403");
        // 自定义拦截器
        Map<String, Filter> filtersMap = new LinkedHashMap<String, Filter>();
        // 限制同一帐号同时在线的个数。
        filtersMap.put("kickout", kickoutSessionFilter());
        shiroFilterFactoryBean.setFilters(filtersMap);
        // 拦截器.
        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>();
        // 配置退出 过滤器,其中的具体的退出代码Shiro已经替我们实现了
        filterChainDefinitionMap.put("/logout", "anon");
        filterChainDefinitionMap.put("/loginPC", "anon");
        filterChainDefinitionMap.put("/master/login", "anon");
        filterChainDefinitionMap.put("/master/kickout", "anon");

        filterChainDefinitionMap.put("/login.shtml", "anon");
        filterChainDefinitionMap.put("/plugins/**", "anon");
        filterChainDefinitionMap.put("/druid/**", "anon");

        filterChainDefinitionMap.put("/doc.html", "anon");// swagger-ui页面
        filterChainDefinitionMap.put("/v2/**", "anon");// swagger-ui页面
        filterChainDefinitionMap.put("/swagger-resources/**", "anon");// swagger-ui页面
        filterChainDefinitionMap.put("/webjars/**", "anon");// swagger-ui页面

        filterChainDefinitionMap.put("/ueditor/**", "anon");// ueditor配置路径
        filterChainDefinitionMap.put("/X-admin/**", "anon");//V1.0相关资源文件

        filterChainDefinitionMap.put("/upload/**", "anon");
        filterChainDefinitionMap.put("/uploads/**", "anon");
        filterChainDefinitionMap.put("/export/**", "anon");

        filterChainDefinitionMap.put("/wechat", "anon");//微信回调 controller
        filterChainDefinitionMap.put("/test/**", "anon");//test controller
        filterChainDefinitionMap.put("/api/**", "anon");//api controller
        filterChainDefinitionMap.put("/cmBlogApi/**", "anon");//blog controller


        filterChainDefinitionMap.put("/**", "anon");
//		filterChainDefinitionMap.put("/**", "authc,kickout");

        // <!-- 过滤链定义，从上向下顺序执行，一般将 /**放在最为下边 -->:这是一个坑呢，一不小心代码就不好使了;
        // <!-- authc:所有url都必须认证通过才可以访问; anon:所有url都都可以匿名访问-->
        // 自定义加载权限资源关系
        /*
         * List<Resources> resourcesList = resourcesService.queryAll(); for
         * (Resources resources : resourcesList) {
         *
         * if (StringUtil.isNotEmpty(resources.getResurl())) { String permission
         * = "perms[" + resources.getResurl() + "]";
         * filterChainDefinitionMap.put(resources.getResurl(), permission); } }
         */
        // filterChainDefinitionMap.put("/**", "authc");

        shiroFilterFactoryBean.getFilters().put("authc", new SimpleFormAuthenticationFilter());

        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
        return shiroFilterFactoryBean;
    }


    //重要！！定义token与Realm关系，设置认证策略
    @Bean
    public MyModularRealmAuthenticator myModularRealmAuthenticator() {
        MyModularRealmAuthenticator authenticator = new MyModularRealmAuthenticator();
        FirstSuccessfulStrategy strategy = new FirstSuccessfulStrategy();
        authenticator.setAuthenticationStrategy(strategy);
        return authenticator;
    }

    @Bean
    public MyShiroRealm shiroRealmSysAdmin() {
        MyShiroRealm shiroRealmSysAdmin = new MyShiroRealm();
        return shiroRealmSysAdmin;
    }

    @Bean
    public MyShiroRealm shiroRealmShopAdmin() {
        MyShiroRealm shiroRealmShopAdmin = new MyShiroRealm();
        shiroRealmShopAdmin.setCredentialsMatcher(new WxHashedCredentialsMatcher());
        return shiroRealmShopAdmin;
    }

    @Bean
    public SecurityManager securityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();

        //设置认证策略
        securityManager.setAuthenticator(myModularRealmAuthenticator());

        Collection<Realm> realms = new ArrayList<>(2);
        //管理员登录
        realms.add(shiroRealmSysAdmin());
        //店铺用户登录
        realms.add(shiroRealmShopAdmin());
        securityManager.setRealms(realms);

        // 自定义缓存实现 使用redis
        securityManager.setCacheManager(cacheManager());
        // 自定义session管理 使用redis
        securityManager.setSessionManager(sessionManager());
        // 注入【记住我】管理器
        securityManager.setRememberMeManager(rememberMeManager());
        return securityManager;
    }


    /**
     * cookie对象
     *
     * @return
     */
    public SimpleCookie rememberMeCookie() {
        // 这个参数是cookie的名称，对应前端的checkbox的name = rememberMe
        SimpleCookie simpleCookie = new SimpleCookie("rememberMe");
        // <!-- 记住我cookie生效时间30天 ,单位秒;-->
        simpleCookie.setMaxAge(2592000);
        simpleCookie.setHttpOnly(true);
        return simpleCookie;
    }

    /**
     * cookie管理对象;记住我功能
     *
     * @return
     */
    public CookieRememberMeManager rememberMeManager() {
        CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager();
        cookieRememberMeManager.setCookie(rememberMeCookie());
        // rememberMe cookie加密的密钥 建议每个项目都不一样 默认AES算法 密钥长度(128 256 512 位)
        AesCipherService aesCipherService = new AesCipherService();
        cookieRememberMeManager.setCipherKey(
                Base64.decode(
                        java.util.Base64.getEncoder()
                                .encodeToString(
                                        aesCipherService.generateNewKey().getEncoded()
                                )
                )
        );
        return cookieRememberMeManager;
    }

    /**
     * 开启shiro aop注解支持. 使用代理方式;所以需要开启代码支持;
     *
     * @param securityManager securityManager
     * @return AuthorizationAttributeSourceAdvisor
     */
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }

    /**
     * 配置shiro redisManager 使用的是shiro-redis开源插件
     *
     * @return
     */
    public RedisManager redisManager() {
        RedisManager redisManager = new RedisManager();
        redisManager.setHost(host);
        redisManager.setPort(port);
        // 配置缓存过期时间
        redisManager.setExpire(180000);
        redisManager.setPassword(password);
        return redisManager;
    }

    /**
     * cacheManager 缓存 redis实现 使用的是shiro-redis开源插件
     *
     * @return
     */
    public RedisCacheManager cacheManager() {
        RedisCacheManager redisCacheManager = new RedisCacheManager();
        redisCacheManager.setRedisManager(redisManager());
        return redisCacheManager;
    }

    /**
     * RedisSessionDAO shiro sessionDao层的实现 通过redis 使用的是shiro-redis开源插件
     */
    @Bean
    public RedisSessionDAO redisSessionDAO() {
        RedisSessionDAO redisSessionDAO = new RedisSessionDAO();
        redisSessionDAO.setRedisManager(redisManager());
        return redisSessionDAO;
    }

    /**
     * shiro session的管理
     */
    @Bean
    public DefaultWebSessionManager sessionManager() {

        SessionConfig sessionManager = new SessionConfig();
        // 会话超时时间，单位：毫秒
        sessionManager.setGlobalSessionTimeout(60 * 60 * 1000);
        // 定时清理失效会话, 清理用户直接关闭浏览器造成的孤立会话
        sessionManager.setSessionValidationInterval(60 * 60 * 1000);
        // 是否开启定时清理失效会话
        sessionManager.setSessionValidationSchedulerEnabled(true);
        // 指定sessionId
        sessionManager.setSessionIdCookie(sessionIdCookie());
        // 是否允许将sessionId 放到 cookie 中
        sessionManager.setSessionIdCookieEnabled(true);
        // 是否允许将 sessionId 放到 Url 地址拦中
        sessionManager.setSessionIdUrlRewritingEnabled(false);

        sessionManager.setSessionDAO(redisSessionDAO());
        Collection<SessionListener> listeners = new ArrayList<>();
        listeners.add(new BDSessionListener());
        sessionManager.setSessionListeners(listeners);
        return sessionManager;
    }

    /**
     * 指定本系统sessionid, 问题: 与servlet容器名冲突, 如jetty, tomcat 等默认jsessionid,
     * 当跳出shiro servlet时如error-page容器会为jsessionid重新分配值导致登录会话丢失!
     */
    @Bean
    public SimpleCookie sessionIdCookie() {
        SimpleCookie simpleCookie = new SimpleCookie("shiro.session");
        // 防止xss攻击，窃取cookie内容
        simpleCookie.setHttpOnly(true);
        return simpleCookie;
    }


    /**
     * 限制同一账号登录同时登录人数控制
     *
     * @return
     */
    public KickoutSessionFilter kickoutSessionFilter() {
        KickoutSessionFilter kickoutSessionFilter = new KickoutSessionFilter();
        // 使用cacheManager获取相应的cache来缓存用户登录的会话；用于保存用户—会话之间的关系的；
        // 这里我们还是用之前shiro使用的redisManager()实现的cacheManager()缓存管理
        // 也可以重新另写一个，重新配置缓存时间之类的自定义缓存属性
        kickoutSessionFilter.setCacheManager(cacheManager());
        // 用于根据会话ID，获取会话进行踢出操作的
        kickoutSessionFilter.setSessionManager(sessionManager());
        // 是否踢出后来登录的，默认是false；即后者登录的用户踢出前者登录的用户；踢出顺序。
        kickoutSessionFilter.setKickoutAfter(false);
        // 同一个用户最大的会话数，默认1；比如2的意思是同一个用户允许最多同时两个人登录；
        kickoutSessionFilter.setMaxSession(3);
        // 被踢出后重定向到的地址
        kickoutSessionFilter.setKickoutUrl("/master/kickout");
        return kickoutSessionFilter;
    }
}
